package com.changgou.search.controller;

import com.changgou.search.feign.SkuEsFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

@Controller
@RequestMapping("/search")
public class SearchController {

    @Autowired
    private SkuEsFeign skuEsFeign;

    @GetMapping
    public ModelAndView search(@RequestParam(required = false) Map<String,String> searchMap){
        ModelAndView mv=new ModelAndView("search");
        Map resultMap = skuEsFeign.search(searchMap);
        //搜索结果
        mv.addObject("resultMap",resultMap);

        //搜索参数
        mv.addObject("searchMap",searchMap);

        //将请求参数转换拼接到一个地址中
        String url = mapToUrl(searchMap);

        //返回请求地址url
        mv.addObject("url",url);

        return mv;
    }

    /**
     * 处理请求参数转换为地址
     * @param searchMap
     * @return url地址
     */
    private String mapToUrl(Map<String,String> searchMap){
        String url="/search";
        if (searchMap!=null &&searchMap.size()>0){
            url+="?";
            for (Map.Entry<String, String> entry : searchMap.entrySet()) {
                url+=entry.getKey()+"="+entry.getValue()+"&";
            }
            //删除最后一个
            url = url.substring(0, url.length() - 1);
        }
        return url;
    }

}
